﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace TasksDataXml.Data
{
    abstract public class BaseDataItem : IBaseDataItem
    {
        [XmlIgnore]
        public abstract string Folder { get; }
        [XmlIgnore]
        public abstract string Filename { get; }

        public string GetFolder(string root)
        {
            if (string.IsNullOrEmpty(root))
                return root;

            bool rootIsFile = File.Exists(root);

            var rootDir = rootIsFile ? Path.GetDirectoryName(root) : root;
            if (rootDir != null)
            {
                var dir = Path.Combine(rootDir, Folder);
                var driveLetter = Path.GetPathRoot(dir);
                if (!Directory.Exists(dir) && !string.IsNullOrEmpty(driveLetter))
                    Directory.CreateDirectory(dir);

                return dir;
            }

            return root;
        }

        public abstract void AttachCallbacks(IBaseDataItem parentCategory);

        public string GetFullPath(string root)
        {
            var dir = GetFolder(root);
            return Path.Combine(dir, Filename);
        }

        public virtual IBaseDataItem RemoveItem(IBaseDataItem item)
        {
            return item;
        }

        [XmlIgnore]
        public Func<IBaseDataItem, bool> NotifyParentAdd { get; set; }
        [XmlIgnore]
        public Func<IBaseDataItem, IBaseDataItem> NotifyParentMove { get; set; }

        public virtual void Dispose()
        {
            NotifyParentAdd = null;
            NotifyParentMove = null;
        }
    }
}
